/* eslint-disable no-undef */
/* eslint-disable no-script-url */
/* eslint-disable jsx-a11y/anchor-is-valid */
import React, {
  useState,
  useEffect,
  useMemo,
  useRef,
  useLayoutEffect,
} from 'react';
import { useRequest, usePersistFn } from 'ahooks';
import Swiper from 'swiper';
import Toast from 'light-toast';
import * as clipboard from 'clipboard-polyfill/text';
import ReactDom from 'react-dom';
import FingerprintJS from '@fingerprintjs/fingerprintjs';
import {
  useAppChannelReport,
  useChannelOrigin,
  useOpenInstall,
  usePlatform,
} from '@/common/hooks';
import { empty, getRequestUrlParams } from '@/common/utils';
import Iconfont from '@/components/Iconfont';
import { getAppDownloadLink, submitClickInfo } from '@/service/live';
import LogoPrimary from '@/assets/images/logo_primary.png';
import GroupImage from '@/assets/images/download/group_image.png';
import swiperImage1 from '@/assets/images/download/swiper_image1.png';
import swiperImage2 from '@/assets/images/download/swiper_image2.png';
import swiperImage3 from '@/assets/images/download/swiper_image3.png';

import CourseImage1 from '@/assets/images/download/course_image1.png';
import CourseImage2 from '@/assets/images/download/course_image2.png';
import SafariIcon from '@/assets/images/download/safari.png';

import Tip3 from '@/assets/images/download/tip3.png';
import Tip4 from '@/assets/images/download/tip4.png';

import Tip5 from '@/assets/images/download/tip5.png';
import Tip6 from '@/assets/images/download/tip6.png';
// import G1 from '@/assets/images/download/g1.png';
// import G2 from '@/assets/images/download/g2.png';
// import G3 from '@/assets/images/download/g3.png';
// import G4 from '@/assets/images/download/g4.png';
// import G5 from '@/assets/images/download/g5.png';
// import G6 from '@/assets/images/download/g6.png';

import styles from './style.scss';

const SafariPopover = ({ visible, downloadUrl }) => {
  const { href } = global.location;
  const handleCopy = () => {
    clipboard.writeText(href).then(() => {
      Toast.success('复制成功,去Safari中打开吧~', 2500);
    });
  };
  if (!visible) return null;
  return (
    <div className={styles.safariPopover}>
      <div className={styles.top}>
        <img className={styles.icon} src={SafariIcon} alt="safari" />
        <div className={styles.text}>
          <div>
            该链接只支持
            <span className={styles.red}> Safari </span>
          </div>
          <div>
            请在
            <span className={styles.red}> Safari </span>
            中打开
          </div>
        </div>
      </div>
      <div className={styles.bottom}>
        <div className={styles.content}>
          <input className={styles.input} type="text" value={href} readOnly />
          <button
            className={styles.button}
            type="button"
            onClick={() => {
              handleCopy(downloadUrl);
            }}
          >
            复制
          </button>
        </div>
      </div>
    </div>
  );
};

const DownloadLink = ({ className, useApiDownload, onClick }) => {
  const { wakeupOrInstall } = useOpenInstall();
  const { platform, isIos } = usePlatform();
  const [downloadUrl, setDownloadUrl] = useState('');
  const [visibleSafari, setVisibleSafari] = useState(false);
  const [loading, setLoading] = useState(false);
  const [showWechatTip, setShowWechatTip] = useState(false);
  const ua = window.navigator.userAgent.toLowerCase();
  const isWechatIos = ua.includes('micromessenger');
  const [showBrowser, setShowBrowser] = useState(false);

  const WeChatTip = useMemo(
    () => ReactDom.createPortal(
      <div
        className={styles.iswechartTip}
        style={{ display: showWechatTip ? 'block' : 'none' }}
      >
        <p>点击右上角,选择浏览器打开</p>
        <div className={styles.right} />
      </div>,
      document.body,
    ),
    [showWechatTip],
  );
  const close = () => {
    setShowBrowser(false);
  };
  const OtherBrowser = useMemo(() => (
    <>
      {
        showBrowser ? (
          <section className={styles.showBrowser}>
            <div>
              <p>提示</p>
              <i>
                请使用默认的safari浏览器打开该页面
                即可下载鑫球直播App
              </i>
              <div>
                <span onClick={close}>取消</span>
                <span onClick={close}>确定</span>
              </div>
            </div>
          </section>
        )
          : null
      }
    </>
  ), [showBrowser]);
  const onClickHandle = (e) => {
    if (isWechatIos) {
      // 微信环境且是ios下，显示遮罩层引导出浏览器下载
      setShowWechatTip(true);
      return;
    }

    // 判断是不是移动端iPHone Safair浏览器打开的本页面
    if (isIos && (ua.includes('miniappenable') || ua.includes('fxios') || ua.includes('crios') || ua.includes('baidu') || ua.includes('uc') || ua.includes('edgios') || ua.includes('figer') || ua.includes('mqq') || ua.includes('sogou') || ua.includes('quark') || ua.includes('aliapp'))) {
      // 官方浏览器内核没有这个mobile
      setShowBrowser(true);
      e?.preventDefault();
      return false;
    }
    // alert(ua);
    if (
      /itms-services/.test(downloadUrl)
      && isIos
      && global.navigator.userAgent.indexOf('Safari') < 0
    ) {
      setVisibleSafari(true);
    } else if (isIos && global.navigator.userAgent.indexOf('Safari') >= 0) {
      setTimeout(() => setLoading(true), 1000);
    }
    onClick(e);
    if (!useApiDownload) wakeupOrInstall();
    // e.preventDefault();
    return false;
  };

  useRequest(getAppDownloadLink, {
    ready: useApiDownload,
    onSuccess: (res) => {
      setDownloadUrl(res[platform] || '/download');
    },
  });

  return useMemo(() => {
    if (useApiDownload) {
      if (!downloadUrl) return null;
      if (isWechatIos) {
        return (
          <>
            <div className={className} onClick={onClickHandle}>
              立即下载
            </div>
            {WeChatTip}
          </>
        );
      }
      return (
        <>
          <a
            className={className}
            href={downloadUrl}
            onClick={onClickHandle}
            rel="noreferrer"
          >
            {loading && <span className={styles.loading} />}
            {loading ? '点击安装后，请返回桌面查看' : '立即下载'}
          </a>
          <SafariPopover visible={visibleSafari} downloadUrl={downloadUrl} />
          {OtherBrowser}
        </>
      );
    }

    return (
      <>
        <a className={className} onClick={onClickHandle}>
          {loading && <span className={styles.loading} />}
          {loading ? '点击安装后，请返回桌面查看' : '立即下载'}
        </a>
        {WeChatTip}

        <SafariPopover visible={visibleSafari} downloadUrl={downloadUrl} />
        <>
          {OtherBrowser}
        </>
      </>

    );
  }, [useApiDownload, downloadUrl, visibleSafari, loading, showWechatTip, showBrowser]);
};

DownloadLink.defaultProps = {
  useApiDownload: true,
  onClick: empty,
};

const DownloadPage = () => {
  const swiperArr = [
    {
      title: '足球篮球盛宴',
      label: '赛场比拼，球友集结',
      src: swiperImage1,
    },
    {
      title: '精准赛事分析',
      label: '专业解读精准分析',
      src: swiperImage2,
    },
    {
      title: '火爆体育赛事',
      label: '高清赛事免费观看',
      src: swiperImage3,
    },
  ];
  const courseImageArr = [
    {
      label: `点击下免费安装后，允许<span class=${styles.highlight}>「下载配置文件」</span>后跳转到<span class=${styles.highlight}>「描述文件与设备管理」</span>点击进入下一步。进入<span class=${styles.highlight}>「安装描述文件」</span>后，点击右上角安装`,
      images: [CourseImage1, CourseImage2],
    },
    {
      label: `如果提示描述文件安装失败，请将原有的 <span class=${styles.highlight}>「已安装描述文件」</span>移除后再安装即可\n在网页点击允许下载<span class=${styles.highlight}>「配置描述文件」</span>后自动跳
转至 <span class=${styles.highlight}>「安装描述文件」</span>点击安装。`,
      images: [Tip3, Tip4],
    },
    {
      label: `跳转至在<span class=${styles.highlight}>「警告」</span> 后点击右上角安装，回到桌面查看安装完成即可`,
      images: [Tip5, Tip6],
    },
  ];

  const swiperRef = useRef();
  const [swiperInstance, setSwiperInstance] = useState(null);
  // 初始化swiper
  const initSwiper = usePersistFn(() => {
    if (swiperInstance) {
      swiperInstance.update();
      swiperInstance.slideTo(0);
    } else {
      const instance = new Swiper(swiperRef.current, {
        slidesPerView: 'auto',
        spaceBetween: 0,
        centeredSlides: true,
        loop: true,
        wrapperClass: styles.swiperWrapper,
        slideClass: styles.swiperItem,
        slideActiveClass: styles.swiperItemActive,
        slideDuplicatedActiveClass: styles.swiperItemDuplicateActive,
      });
      setSwiperInstance(instance);
    }
  });

  const { isIos, isAndroid } = usePlatform();
  const [channel] = useChannelOrigin();
  const [onDownloadReportHandle] = useAppChannelReport();
  const { agentId = null } = getRequestUrlParams(window.location.href);

  // 是否使用接口下载 是否用openinstall下载还是直接使用链接 agentId通过其他用户邀请下载 尝试提交给open并且传递参数
  const useApiDownload = useMemo(
    () => (!channel || channel.name !== 'channelCode') && !agentId,
    [channel, agentId],
  );

  // 销毁swiper
  const destroySwiper = () => {
    if (!swiperInstance) return;
    swiperInstance.destroy();
    setSwiperInstance(null);
  };

  const { run: infopush } = useRequest((p) => submitClickInfo(p), {
    onSuccess: () => {

    },
    manual: true,
  });
  const submitInfo = async (p) => {
    const fpPromise = FingerprintJS.load();
    const fp = await fpPromise;
    const result = await fp.get();
    await infopush({ identity: result.visitorId, ...p });
  };
  useEffect(() => {
    if (isIos) {
      submitInfo({ requestType: 1 });
    }
  }, [isIos]);
  const onDownloadHandle = async () => {
    if (isIos) {
      await submitInfo({ requestType: 2 });
      onDownloadReportHandle(5);
    } if (isAndroid) {
      onDownloadReportHandle(3);
    }
    // setChannel('');
  };

  useLayoutEffect(() => {
    initSwiper();
  }, []);

  useEffect(() => {
    if (isIos) {
      onDownloadReportHandle(4);
    } else if (isAndroid) {
      onDownloadReportHandle(2);
    }
    return destroySwiper;
  }, []);

  return (
    <main className={styles.container}>
      <div className={styles.wrapper}>
        <img className={styles.logo} src={LogoPrimary} />
        <img className={styles.group} src={GroupImage} />
        <DownloadLink
          className={styles.downButton}
          useApiDownload={useApiDownload}
          onClick={onDownloadHandle}
        />
        <div className={styles.swiperContainer} ref={swiperRef}>
          <div className={styles.swiperWrapper}>
            {swiperArr.map(({ src, title, label }, index) => (
              <div key={index} className={styles.swiperItem}>
                <div className={styles.title}>{title}</div>
                <span className={styles.label}>{label}</span>
                <img src={src} />
              </div>
            ))}
          </div>
        </div>

        {/* <div className={styles.gife}>
          <div className={styles.gife_content}>
            <p>下载App与主播互动赢取豪礼</p>
            <div className={styles.gife_list}>
              <span>
                <img src={G1} alt="" />
                <span>官方联名同款球衣一件</span>
                <span>根据抽奖场次或随机赠送</span>
              </span>
              <span>
                <img src={G2} alt="" />
                <span>耐克正品足球鞋</span>
              </span>
              <span>
                <img src={G3} alt="" />
                <span>话费充值卡</span>
              </span>
              <span>
                <img src={G4} alt="" />
                <span>NBA官方联名同款篮球鞋</span>
              </span>
              <span>
                <img src={G5} alt="" />
                <span>足球/篮球一个</span>
              </span>
              <span>
                <img src={G6} alt="" />
                <span>纪念礼物</span>
              </span>
            </div>
          </div>
        </div> */}
        <div className={styles.course}>
          <div className={styles.courseTitle}>
            <Iconfont name="ios" className={styles.icon} />
            <span>iOS安装教程</span>
          </div>
          <div className={styles.courseSub}>
            需在统一网络环境下下载安装和注册，切勿切换网络，若无法正常下载，请使用手机自带浏览器打开（Chrome、Safari浏览器）
          </div>
          {courseImageArr.map(({ label, images }, index) => (
            <div key={index} className={styles.courseItem}>
              <i className={styles.badge}>{index + 1}</i>
              {/* eslint-disable-next-line  */}
              <span
                className={styles.courseLabel}
                // eslint-disable-next-line react/no-danger
                dangerouslySetInnerHTML={{ __html: label }}
              />
              <div>
                {images.map((src, imageIndex) => (
                  <img key={imageIndex} src={src} alt="course" />
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </main>
  );
};

export default DownloadPage;
